package com.houdoudou.customer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Car;
import com.houdoudou.bean.Machine;
import com.houdoudou.bean.Supplier;
import com.houdoudou.customer.buy.BuyCarAct;
import com.houdoudou.customer.buy.ShopAct;
import com.houdoudou.customer.common.CommonFunction;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.ListViewUtil;
import com.houdoudou.customer.common.SerializableMap;
import com.houdoudou.customer.common.UniversalHttpPost;
import com.houdoudou.customer.find.SearchMachineActivity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class FrgBuyOfActMain extends Fragment{
		
	TextView pull_result,machineaddress,machinename,machineid;

	ImageButton buy_car,changemachine;
	ProgressBar progres;
	Button repull;
	LinearLayout lt_pullfailed;
	ListView listview_supplier;
	TextView morning,noon,evening;
	MyListAdapter myListAdapter;
	View.OnClickListener myOnclickListener;
	public static JSONArray suppliersJA=new JSONArray();
	private static JSONArray timeSuppliersJA= new JSONArray();
    public static boolean  needPullSupplier=true;
    public static boolean PullSuccess=false;
   
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//return super.onCreateView(inflater, container, savedInstanceState);
		View view=inflater.inflate(R.layout.frg_buy_act_main, container, false);
		init_listener();
		init_component(view);
		System.out.println("---------FrgBuyOfActMain OnCreat----------------");
		needPullSupplier=true;
		return view;
	}
	
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		//  System.out.println("frgbug-------------machine="+Constant.machineJO.toString());
          boolean notMachineConfig=Constant.machineJO==null;
		  if(notMachineConfig){		
				 Intent intent= new Intent(getActivity(), ChooseMachineActivity.class);    	   	   
			     startActivity(intent);		   
			}else{
				   machineaddress.setText(Constant.machineJO.getString(Machine.ADDRESS));
				    machineid.setText("NO."+Constant.machineJO.getInt(Machine.ID));
				    machinename.setText(Constant.machineJO.getString(Machine.NAME));
			}
		  
		if(needPullSupplier&&(!notMachineConfig)){	
			
			  if(CommonFunction.isNetworkAvailble(getActivity())){
				  pull_supplier();
			  }else{
				  Message msg= new Message();
				  msg.what=1;
				  msg.obj=null;
				  CustomerMainActivity.mainHandler.sendMessage(msg);
				  
				  Builder b = new AlertDialog.Builder(getActivity()).setTitle("没有可用的移动网络和wifi")  
						     .setMessage("是否对网络进行设置？");  
						   b.setPositiveButton("设置", new DialogInterface.OnClickListener() {  
						    public void onClick(DialogInterface dialog, int whichButton) {  
						    	/*  Intent mIntent = new Intent("/");  
						     ComponentName comp = new ComponentName(  
						       "com.android.settings",  
						       "com.android.settings.WirelessSettings");  
						     mIntent.setComponent(comp);  
						     mIntent.setAction("android.intent.action.VIEW");  */
						    	//Intent mIntent = new Intent(Settings.ACTION_WIFI_SETTINGS); 
						    	//Intent mIntent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
						    	Intent mIntent = new Intent(Settings.ACTION_SETTINGS); 
						     FrgBuyOfActMain.this.startActivity(mIntent);   
						    }  
						   })
						   .setNegativeButton("重试",new DialogInterface.OnClickListener() {  
							    public void onClick(DialogInterface dialog, int whichButton) {  
								     dialog.cancel();   onResume();
								   
								    }  
						   }).show();  
			  }
			
		}
		super.onResume();	
	}
	     private void    pull_supplier(){		
			    progres.setVisibility(View.VISIBLE);
				listview_supplier.setVisibility(View.GONE);
				lt_pullfailed.setVisibility(View.GONE);
				String[] params= new String[5];
	            params[0]=Constant.BaseUrl+Constant.CustomerUrl;
                params[1]="searchSupplier"; //PostCod
                JSONObject jsonData=new JSONObject();
                JSONObject machineJO=new JSONObject();	
                machineJO.put("id", Constant.machineJO.getInt(Machine.ID));
	            jsonData.put("machine", machineJO);
               params[2]=jsonData.toString();
             new HttpPostTaskforPollSupplier().execute(params);
	        }
	
	private void init_listener(){
		
		
		/////////////////////////////////////////////////////////////////
			
			myOnclickListener= new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
					if(v==buy_car){
						Intent intent= new Intent(getActivity(), BuyCarAct.class);  						
						startActivity(intent);
					    }				
				   if(v==repull){
					   pull_supplier();
				   }
				   if(v==changemachine){
					   Intent intent= new Intent(getActivity(), SearchMachineActivity.class);  						
						startActivity(intent); 
				   }
				   if(v==morning||v==noon|v==evening){
					   morning.setBackgroundColor(Color.GRAY);  noon.setBackgroundColor(Color.GRAY);  evening.setBackgroundColor(Color.GRAY);
					   int timeFlag=0; 
					   if(v==morning){ timeFlag=1; 
					   morning.setBackgroundColor(Color.WHITE); }
					   if(v==noon){
						   timeFlag=2;
						   noon.setBackgroundColor(Color.WHITE);}
					   if(v==evening){ timeFlag=3;
					     evening.setBackgroundColor(Color.WHITE);}
					   timeSuppliersJA.clear();
					   for(int i=0;i<suppliersJA.size();i++){
						   if(suppliersJA.getJSONObject(i).getInt(Car.TIMEFLAG)==timeFlag){
							   timeSuppliersJA.add(suppliersJA.getJSONObject(i));
						   }
					   }
					   myListAdapter.notifyDataSetChanged();
					   ListViewUtil.setListViewHeightBasedOnChildren(listview_supplier);
					 System.out.println("timeSuppliersJA.size() = "+timeSuppliersJA.size());  
				   }
				   
				               }// onClick			
			                      };					
		           }
		
		
		private void init_component(View view){
			
			
			buy_car= (ImageButton)  view.findViewById(R.id.imgbtn_buycar_frg_buy_mainact);
			progres= (ProgressBar)view.findViewById(R.id.prgs_frg_buy_mainact);
			listview_supplier= (ListView) view.findViewById(R.id.list_frg_buy_mainact);
			pull_result= (TextView) view.findViewById(R.id.pullresult_frg_buy_mainact);
			repull= (Button) view.findViewById(R.id.btn_repull_frg_buy_mainact);
			lt_pullfailed= (LinearLayout) view.findViewById(R.id.lt_pullfailed_frg_buy_mainact);
			machineaddress= (TextView) view.findViewById(R.id.tv_machineaddress_frg_buy_mainact);
			machinename=(TextView) view.findViewById(R.id.tv_machinename_frg_buy_mainact);
			machineid=(TextView) view.findViewById(R.id.tv_machineid_frg_buy_mainact);
			changemachine= (ImageButton) view.findViewById(R.id.imgbtn_changemachine_frg_buy_mainact);
			
			morning= (TextView) view.findViewById(R.id.tv_morning_frg_buy_mainact);
			noon= (TextView) view.findViewById(R.id.tv_noon_frg_buy_mainact);
			evening= (TextView) view.findViewById(R.id.tv_evening_frg_buy_mainact);
			//////////////////////
			
			repull.setOnClickListener(myOnclickListener);
			buy_car.setOnClickListener(myOnclickListener);
		    changemachine.setOnClickListener(myOnclickListener);
		     
		    morning.setOnClickListener(myOnclickListener);
		    noon.setOnClickListener(myOnclickListener);
		    evening.setOnClickListener(myOnclickListener);
			
		    lt_pullfailed.setVisibility(View.GONE);
		    progres.setVisibility(View.GONE);
			myListAdapter= new MyListAdapter(getActivity());
			listview_supplier.setAdapter(myListAdapter);
			ListViewUtil.setListViewHeightBasedOnChildren(listview_supplier);
			listview_supplier.setOnItemClickListener(new AdapterView.OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position,
						long id) {
				//	String temp=(String) suppliersJA.getJSONObject(position).get("Supplier_Telnum");	
					  Intent intent= new Intent(getActivity(), ShopAct.class);  			 
					  Bundle bundle= new Bundle();
				           bundle.putString("supplier", timeSuppliersJA.getJSONObject(position).toString());
					  intent.putExtras(bundle);
					     startActivity(intent);
					
				}
				
			});
			
		}
		
	private  class HttpPostTaskforPollSupplier extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
		
			 progres.setVisibility(View.GONE);	
			 Message msg= new Message();
			 msg.what=1;
		    CustomerMainActivity.mainHandler.sendMessage(msg); 
			  
			 System.out.println("-----------onPostExecute()--------------");
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				  lt_pullfailed.setVisibility(View.VISIBLE);
				  pull_result.setText("无法连接服务器");
		               return;
			}
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean ActionStatus=false;
				String ErrorInfo="";
				JSONObject json = null;
				 JSONArray Suppliers = null;
				try{
			     json= JSONObject.fromObject(PostResult);
				 ActionStatus=json.getBoolean("success");
				 ErrorInfo=json.getString("errorInfo");					
				}catch(JSONException e){
					 lt_pullfailed.setVisibility(View.VISIBLE);
					  pull_result.setText("数据解析错误");
					  return;
				}
				
				 if(ErrorInfo.equals("自提柜暂停运营")){
					 
					  Builder b = new AlertDialog.Builder(getActivity()).setTitle(Constant.machineJO.getString(Machine.NAME)+"暂停运营")  
							     .setMessage("是否重新选择自提柜？");  
							   b.setPositiveButton("是", new DialogInterface.OnClickListener() {  
							    public void onClick(DialogInterface dialog, int whichButton) {  
							    	
							    	 Intent intent= new Intent(getActivity(), ChooseMachineActivity.class);    
							     FrgBuyOfActMain.this.startActivity(intent);   
							    }  
							   }).setNegativeButton("否",new DialogInterface.OnClickListener() {  
								    public void onClick(DialogInterface dialog, int whichButton) {  
									     dialog.cancel();  
									   
									    }  
							   })
							   .show();  			   
				 }
		       if(!ActionStatus){
	            	 lt_pullfailed.setVisibility(View.VISIBLE);
	            	 pull_result.setText(ErrorInfo); 
	            	 return;
	             } // ifActionStatus	
		         
		    	    //拉取一次就不再拉取
		    	     PullSuccess=true;
		    	     needPullSupplier=false;
		    	     Suppliers= json.getJSONArray("suppliers");
					  if(Suppliers.size()<=0) {
						  lt_pullfailed.setVisibility(View.VISIBLE);
						  repull.setVisibility(View.GONE);
						  pull_result.setText("本机没有货物出售");
						  }else{
							  lt_pullfailed.setVisibility(View.GONE);
							  listview_supplier.setVisibility(View.VISIBLE);
							  suppliersJA.clear();
							  suppliersJA=Suppliers;
							 System.out.println("after search  suppliersJA.size()="+suppliersJA.size());
							 morning.performClick();
						 //    myListAdapter.notifyDataSetChanged(); 
							 
						  }	    	 		    	   
		    	     	
			 
		} //onPostExecute
 } //AsyncTask
	class MyListAdapter extends BaseAdapter {
		   
		
		    private LayoutInflater layoutInflater;  
		    private Context context;  
		    
		public MyListAdapter(Context context) {
				super();
				
				this.context = context;
			    this.layoutInflater=LayoutInflater.from(context); 
			}
		
		
		final class Zujian{  
		    public TextView major,name,telnum,sale_total,product_total,arrive_time, minute_noorder;  
	       
	        public ImageView supplier_pic;
	      
	    
	   }   //end of Zujian

		@Override 
		public int getCount() {
			// TODO Auto-generated method stub
			 System.out.println("WHEN LAYOUT LIST timeSuppliersJA.size()="+timeSuppliersJA.size()); 
			 return timeSuppliersJA.size();  
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			 return timeSuppliersJA.getJSONObject(position);  
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position; 
		}
	 
		@Override
		public View getView(int position, View  convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int selectID = position;   
			 Zujian zj=null;  
		        if(convertView==null){  
		            zj=new Zujian();  
		            //获得组件，实例化组件  
		            convertView=layoutInflater.inflate(R.layout.list_supplier_frg_buy_act_main, null);  		          
		            zj.name=(TextView) convertView.findViewById(R.id.tv_name_list_supplier_frg_buy);
		            zj.major=(TextView) convertView.findViewById(R.id.tv_business_list_supplier_frg_buy); 
		            zj.telnum=(TextView) convertView.findViewById(R.id.tv_telnum_list_supplier_frg_buy); 
		            zj.sale_total= (TextView) convertView.findViewById(R.id.tv_salenum_list_supplier_frg_buy);
		            zj.minute_noorder=(TextView) convertView.findViewById(R.id.tv_time_no_order_list_supplier_frg_buy);
		            zj.arrive_time=(TextView) convertView.findViewById(R.id.tv_time_list_supplier_frg_buy);
		            zj.product_total=(TextView) convertView.findViewById(R.id.tv_productnum_list_supplier_frg_buy);		            
		            zj.supplier_pic=(ImageView) convertView.findViewById(R.id.img_list_supplier_frg_buy);     		                 
		            convertView.setTag(zj);  
		            System.out.println("position----"+selectID+"------inflated");
		        }else{   System.out.println("position----"+selectID+"-------not inflated");
		            zj=(Zujian)convertView.getTag();  
		        }  			  
		        //绑定数据  
		        zj.name.setText("店铺："+timeSuppliersJA.getJSONObject(selectID).getString(Supplier.NAME));
		        zj.major.setText("主营："+ timeSuppliersJA.getJSONObject(selectID).getString(Supplier.MAJOR));
		        zj.telnum.setText("电话："+ timeSuppliersJA.getJSONObject(selectID).getString(Supplier.SERVICETELNUM));
		        zj.sale_total.setText("销量："+timeSuppliersJA.getJSONObject(selectID).getInt("saleNum"));  
		        zj.minute_noorder.setText("提前下单："+timeSuppliersJA.getJSONObject(selectID).getInt(Supplier.MINUTEMINI)+"分钟");  
		        zj.arrive_time.setText("送达时间："+ timeSuppliersJA.getJSONObject(selectID).getString("timeAA"));  
		        zj.product_total.setText("数量："+timeSuppliersJA.getJSONObject(selectID).getInt("productNum"));  
		             
		        zj.supplier_pic.setImageResource(R.drawable.machine_list);
		        return convertView;
	           } 
	      }// end Adapter

	
}
